<template>
  <view class="order-confirm">
    <!-- 使用系统默认导航栏 -->
    
    <!-- 地址选择 -->
    <view class="order-address">
      <address-picker 
        :address="selectedAddress" 
        @select="selectAddress"
      />
    </view>
    
    <!-- 服务信息 -->
    <order-section title="服务信息">
      <view class="service-info">
        <image class="service-image" :src="serviceDetail.image" mode="aspectFill" />
        <view class="service-detail">
          <view class="service-title">{{ serviceDetail.title }}</view>
          <view class="service-option">{{ selectedOption.name }}</view>
          <view class="service-price">{{ selectedOption.price }}</view>
        </view>
      </view>
      <view class="service-time">
        <text class="service-time__label">服务时间</text>
        <text class="service-time__value">{{ selectedTime }}</text>
      </view>
    </order-section>
    
    <!-- 订单备注 -->
    <order-section title="订单备注">
      <input 
        class="order-remark" 
        placeholder="请输入备注信息（选填）" 
        v-model="remark"
      />
    </order-section>
    
    <!-- 订单金额 -->
    <order-section title="订单金额">
      <view class="order-price-item">
        <text class="order-price-label">服务费用</text>
        <text class="order-price-value">{{ orderPrice.servicePrice }}</text>
      </view>
      <view class="order-price-item" v-if="orderPrice.discount > 0">
        <text class="order-price-label">优惠金额</text>
        <text class="order-price-value discount">-{{ orderPrice.discount }}</text>
      </view>
      <view class="order-price-total">
        <text class="order-price-label">实付金额</text>
        <text class="order-price-value total">{{ orderPrice.totalPrice }}</text>
      </view>
    </order-section>
    
    <!-- 支付方式 -->
    <order-section title="支付方式">
      <view 
        v-for="(method, index) in paymentMethods" 
        :key="index"
        class="payment-method"
        :class="{ 'active': selectedPayment === index }"
        @click="selectPayment(index)"
      >
        <view class="payment-method__left">
          <text class="payment-method__icon">{{ method.icon }}</text>
          <text class="payment-method__name">{{ method.name }}</text>
        </view>
        <view class="payment-method__right">
          <text class="payment-method__circle" :class="{ 'active': selectedPayment === index }"></text>
        </view>
      </view>
    </order-section>
    
    <!-- 底部支付栏 -->
    <view class="order-footer">
      <view class="order-footer__price">
        <text class="order-footer__price-label">实付金额：</text>
        <text class="order-footer__price-value">{{ orderPrice.totalPrice }}</text>
      </view>
      <view class="order-footer__btn" @click="submitOrder">
        立即支付
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue';
import OrderSection from '@/components/service/OrderSection.vue';
import AddressPicker from '@/components/service/AddressPicker.vue';

// 获取传入的参数
const options = ref(null);
const serviceId = ref(null);
// 初始化为默认对象，防止null错误
const selectedOption = ref({
  id: 0,
  name: '加载中...',
  price: '¥0'
});
const selectedTime = ref('加载中...');

// 地址相关
const selectedAddress = ref(null);
const userAddresses = ref([
  {
    id: 1,
    name: '张三',
    phone: '134****5678',
    province: '广东省',
    city: '广州市',
    district: '天河区',
    detail: '五山路华南理工大学C12学生公寓',
    isDefault: true
  },
  {
    id: 2,
    name: '李四',
    phone: '187****1234',
    province: '广东省',
    city: '广州市',
    district: '海珠区',
    detail: '新港西路100号',
    isDefault: false
  }
]);

// 服务信息
const serviceDetail = reactive({
  id: 0,
  title: '',
  image: '',
  price: ''
});

// 订单相关
const remark = ref('');
const orderPrice = reactive({
  servicePrice: '¥0',
  discount: '¥0',
  totalPrice: '¥0'
});

// 支付方式
const paymentMethods = [
  { icon: '💰', name: '余额支付' },
  { icon: '💳', name: '微信支付' },
  { icon: '💴', name: '支付宝支付' }
];
const selectedPayment = ref(0);

// 生命周期钩子
onMounted(() => {
  // 获取页面参数
  const pages = getCurrentPages();
  const currentPage = pages[pages.length - 1];
  options.value = currentPage.options;
  
  console.log('订单确认页参数:', options.value);
  
  if (options.value && options.value.serviceId) {
    // 设置服务ID
    serviceId.value = options.value.serviceId;
    
    // 设置选中的服务时间
    if (options.value.time) {
      try {
        selectedTime.value = decodeURIComponent(options.value.time);
      } catch (e) {
        console.error('解析时间参数失败:', e);
      }
    }
    
    // 先根据参数初始化selectedOption
    if (options.value.optionId) {
      console.log('选项ID:', options.value.optionId);
    }
    
    // 加载服务详情
    loadServiceDetail(serviceId.value);
    
    // 加载默认地址
    loadDefaultAddress();
    
    // 计算价格
    calculatePrice();
  } else {
    uni.showToast({
      title: '参数错误',
      icon: 'none'
    });
  }
});

// 加载服务详情
const loadServiceDetail = (id) => {
  console.log('加载服务ID:', id);
  
  // 模拟数据
  serviceDetail.id = id;
  serviceDetail.title = '快递代拿服务';
  serviceDetail.image = '/static/images/service1.jpg';
  serviceDetail.price = '¥5.00';

  // 根据optionId设置选项
  if (options.value && options.value.optionId) {
    const optionId = Number(options.value.optionId);
    // 模拟不同的选项数据
    const availableOptions = [
      { id: 0, name: '普通件 (0-2kg)', price: '¥5.00' },
      { id: 1, name: '大件 (2-5kg)', price: '¥8.00' },
      { id: 2, name: '特大件 (5kg以上)', price: '¥12.00' }
    ];
    
    // 查找对应的选项
    const option = availableOptions.find(opt => opt.id === optionId) || availableOptions[0];
    selectedOption.value = option;
  }
  
  return Promise.resolve();
};

// 加载默认地址
const loadDefaultAddress = () => {
  const defaultAddress = userAddresses.value.find(addr => addr.isDefault);
  if (defaultAddress) {
    selectedAddress.value = defaultAddress;
  } else if (userAddresses.value.length > 0) {
    selectedAddress.value = userAddresses.value[0];
  }
};

// 计算订单价格
const calculatePrice = () => {
  if (selectedOption.value && selectedOption.value.price) {
    const priceStr = selectedOption.value.price;
    const priceNum = Number(priceStr.replace('¥', ''));
    
    orderPrice.servicePrice = `¥${priceNum}`;
    orderPrice.discount = '¥0';
    orderPrice.totalPrice = `¥${priceNum}`;
    
    console.log('已计算价格:', orderPrice);
  } else {
    console.error('计算价格失败，选项无效:', selectedOption.value);
  }
};

// 选择地址
const selectAddress = () => {
  uni.navigateTo({
    url: '/pages/me/address/index?select=1'
  });
};

// 选择支付方式
const selectPayment = (index) => {
  selectedPayment.value = index;
};

// 提交订单
const submitOrder = () => {
  if (!selectedAddress.value) {
    uni.showToast({
      title: '请选择收货地址',
      icon: 'none'
    });
    return;
  }
  
  // 显示加载中
  uni.showLoading({
    title: '提交订单中'
  });
  
  // 模拟请求延迟
  setTimeout(() => {
    uni.hideLoading();
    
    // 随机生成订单号
    const orderId = `ORDER${Date.now()}${Math.floor(Math.random() * 1000)}`;
    
    // 跳转到支付结果页面
    uni.navigateTo({
      url: `/pages/service/payment-result?orderId=${orderId}&status=success`
    });
  }, 1500);
};

// 返回上一页
const goBack = () => {
  uni.navigateBack();
};
</script>

<style lang="scss" scoped>
.order-confirm {
  background-color: #f5f5f5;
  min-height: 100vh;
  padding-top: 44px;
  padding-bottom: 100px;
}

.order-address {
  background-color: #fff;
  margin-bottom: 10px;
}

.service-info {
  display: flex;
  margin-bottom: 15px;
}

.service-image {
  width: 80px;
  height: 80px;
  border-radius: 4px;
  margin-right: 10px;
}

.service-detail {
  flex: 1;
}

.service-title {
  font-size: 15px;
  color: #333;
  margin-bottom: 5px;
  line-height: 1.4;
}

.service-option {
  font-size: 13px;
  color: #666;
  margin-bottom: 5px;
}

.service-price {
  font-size: 16px;
  color: #f56c6c;
  font-weight: bold;
}

.service-time {
  display: flex;
  font-size: 14px;
  margin-top: 10px;
  padding-top: 10px;
  border-top: 1px solid #f2f2f2;
  
  &__label {
    color: #666;
    min-width: 70px;
  }
  
  &__value {
    color: #333;
    flex: 1;
  }
}

.order-remark {
  width: 100%;
  height: 40px;
  font-size: 14px;
}

.order-price-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
  font-size: 14px;
}

.order-price-label {
  color: #666;
}

.order-price-value {
  color: #333;
  
  &.discount {
    color: #f56c6c;
  }
  
  &.total {
    color: #f56c6c;
    font-weight: bold;
  }
}

.order-price-total {
  display: flex;
  justify-content: space-between;
  margin-top: 15px;
  padding-top: 15px;
  border-top: 1px solid #f2f2f2;
  font-size: 15px;
  font-weight: bold;
}

.payment-method {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 0;
  border-bottom: 1px solid #f2f2f2;
  
  &:last-child {
    border-bottom: none;
  }
  
  &__left {
    display: flex;
    align-items: center;
  }
  
  &__icon {
    font-size: 20px;
    margin-right: 10px;
  }
  
  &__name {
    font-size: 14px;
    color: #333;
  }
  
  &__right {
    display: flex;
    align-items: center;
  }
  
  &__circle {
    width: 18px;
    height: 18px;
    border-radius: 50%;
    border: 1px solid #ddd;
    display: flex;
    align-items: center;
    justify-content: center;
    position: relative;
    
    &.active {
      border-color: #07c160;
      
      &:after {
        content: '';
        width: 10px;
        height: 10px;
        border-radius: 50%;
        background-color: #07c160;
        position: absolute;
      }
    }
  }
}

.order-footer {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 50px;
  display: flex;
  align-items: center;
  background-color: #fff;
  border-top: 1px solid #f2f2f2;
  padding: 0 15px;
}

.order-footer__price {
  flex: 1;
  display: flex;
  align-items: center;
}

.order-footer__price-label {
  font-size: 14px;
  color: #666;
}

.order-footer__price-value {
  font-size: 18px;
  color: #f56c6c;
  font-weight: bold;
}

.order-footer__btn {
  width: 120px;
  height: 40px;
  background-color: #07c160;
  color: #fff;
  font-size: 15px;
  border-radius: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>
